/**
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package us.levk.remote.drmaa.common.communication;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import org.apache.xmlrpc.common.TypeFactoryImpl;
import org.apache.xmlrpc.common.XmlRpcController;
import org.apache.xmlrpc.common.XmlRpcStreamConfig;
import org.apache.xmlrpc.serializer.SerializableSerializer;
import org.apache.xmlrpc.serializer.TypeSerializer;
import org.apache.xmlrpc.serializer.TypeSerializerImpl;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;


/**
 * @author levk
 *
 */
public class ExtendedTypeFactory extends TypeFactoryImpl {

  private static final transient TypeSerializerImpl SET_SERIALIZER = new SerializableSerializer () {

    /* (non-Javadoc)
     * @see org.apache.xmlrpc.serializer.SerializableSerializer#write(org.xml.sax.ContentHandler, java.lang.Object)
     */
    @SuppressWarnings ("unchecked") @Override public void write (ContentHandler pHandler, Object pObject) throws SAXException {
      if (!(pObject instanceof Serializable)) {
        HashSet<Object> tmp = new HashSet<Object> ();
        tmp.addAll ((Set<Object>) pObject);
        pObject = tmp;
      }
      super.write (pHandler, pObject);
    }
  };

  /**
   * @param pController
   */
  public ExtendedTypeFactory (XmlRpcController pController) { super (pController); }

  /* (non-Javadoc)
   * @see org.apache.xmlrpc.common.TypeFactoryImpl#getSerializer(org.apache.xmlrpc.common.XmlRpcStreamConfig, java.lang.Object)
   */
  @Override public TypeSerializer getSerializer (XmlRpcStreamConfig pConfig, Object pObject) throws SAXException {
    TypeSerializer result = super.getSerializer (pConfig, pObject);
    if (result == null && pObject instanceof Set) return SET_SERIALIZER;
    return result;
  }
}
